/**
 * ReportGear(2011)
 */
package net.abbp.report.view.grid;

import javax.swing.JScrollBar;

import net.abbp.report.view.GridView;

/**
 * Grid滚动条
 * 
 * @version 1.0 2011-3-14
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 * 
 */
public class DynamicScrollBar extends JScrollBar {

    /**
     * UID
     */
    private static final long serialVersionUID = -2775143151103635774L;
    // 对应工作簿
    private GridView gridView;

    public DynamicScrollBar(int orientation, GridView gridView) {
        super(orientation);

        this.gridView = gridView;
        this.setMinimum(0);
        this.setUnitIncrement(1);
        this.setBlockIncrement(10);
    }

    @Override
    public int getVisibleAmount() {
        if (this.gridView == null) {
            return 0;
        }
        if (orientation == JScrollBar.VERTICAL) {
            return this.getVerticalExtent(this.getValue());
        } else {
            return this.getHorizontalExtent(this.getValue());
        }
    }

    @Override
    public int getValue() {
        if (this.gridView == null) {
            return super.getValue();
        }
        if (orientation == JScrollBar.VERTICAL) {
            return this.gridView.getVertBeginValue();
        } else {
            return this.gridView.getHoriBeginValue();
        }
    }

    @Override
    public void setValue(int value) {
        if (this.gridView == null) {
            super.setValue(value);

            return;
        }

        int v = value;
        if (v < 0) {
            v = 0;
        }

        if (orientation == JScrollBar.VERTICAL) {
            v = Math.min(v, this.gridView.getRowCount());
            this.gridView.setVertBeginValue(v);
        } else {
            v = Math.min(v, this.gridView.getColumnCount());
            this.gridView.setHoriBeginValue(v);
        }

        this.gridView.refresh();
    }

    private int getVerticalExtent(int index) {
        return this.gridView.getVertValueExtend();
    }

    private int getHorizontalExtent(int index) {
        return this.gridView.getHoriValueExtend();
    }
}